﻿ package  {
	import gs.TweenLite;
	import fl.controls.ColorPicker;
    import fl.events.ColorPickerEvent;
	
    import flash.display.Sprite;
    import flash.text.TextField;
	import flash.filters.GlowFilter;
	import flash.events.Event;
    import org.papervision3d.cameras.Camera3D;
	import org.papervision3d.render.BasicRenderEngine;
    import org.papervision3d.scenes.Scene3D;
    import org.papervision3d.view.Viewport3D;
	import org.papervision3d.events.FileLoadEvent;
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.objects.parsers.*;
	import org.papervision3d.core.proto.DisplayObjectContainer3D;
	import org.papervision3d.core.geom.renderables.Vertex3D;
	import org.papervision3d.core.math.*;
	import org.papervision3d.materials.ColorMaterial;
	import org.papervision3d.materials.utils.MaterialsList;
	import org.papervision3d.core.proto.MaterialObject3D;
	import org.papervision3d.lights.PointLight3D;
	import org.papervision3d.materials.shadematerials.GouraudMaterial
    import org.papervision3d.core.proto.LightObject3D;
			
	
    public class CustomVp extends Sprite {
		//remove dae
		private var c_parent:DisplayObjectContainer3D;
    	public var vpCustom:Viewport3D = new Viewport3D(550,400);
        public var sCustom:Scene3D = new Scene3D();
        public var cCustom:Camera3D = new Camera3D();
        public var renderer:BasicRenderEngine = new BasicRenderEngine();
		public var object:DAE;
		private var colorPicker:ColorPicker = new ColorPicker();
		//creat a light in scene
		private var light:PointLight3D = new PointLight3D(true);
		//khai bao bien dung chung cho class custom
		public static var dae1:DisplayObject3D;
		private var dae2:DisplayObject3D;
		public static var dae3:DisplayObject3D;
		public static var dae4:DisplayObject3D;
		private var dae5:DisplayObject3D;
		private var dae6:DisplayObject3D;
		private var dae7:DisplayObject3D;
		private var dae8:DisplayObject3D;
		private var dae9:DisplayObject3D;
		private var dae10:DisplayObject3D;
		
		private var maxX :Number = 0;
		private var minX :Number = 0;
		private var maxY :Number = 0;
		private var minY :Number = 0;
		private var maxZ :Number = 0;
		private var minZ :Number = 0;
		public var text:Array = new Array('khung','duoi', 'kieng_left', 'kieng_right','banhtruoc_left','banhtruoc_right', 'banhsau_left', 'banhsau_right','default_matden','default_material');
		public static var bien:int=100;
		public var isBoolean: Boolean= false;
		
		public function CustomVp(){
			
			addChild(vpCustom);
			vpCustom.interactive=true;
			//vpCustom.filters = [new GlowFilter(0xcc0000, 1, 10, 10, 2)];
			vpCustom.opaqueBackground = 0x000000;
         	
			
        }
		private function setInteractiveMaterials(targetObject:DisplayObject3D, value:Boolean):void
	{
	 if(targetObject.materials.numMaterials>0) {
                for(var i:String in targetObject.materials.materialsByName) {
                    (targetObject.materials.materialsByName[i] as MaterialObject3D).interactive = true;
                }
            } else if(targetObject.material) {
                targetObject.material.interactive = true;
            }
}
		private function parseMesh(obj:DisplayObject3D):void
		{

			maxX =0;
			maxY =0;
			maxZ =0;
			var i:Number=0;
			for each(var vertex:Vertex3D in obj.geometry.vertices)
		{
			i++;
			var vx:Number = vertex.x;
			var vy:Number = vertex.y;
			var vz:Number = vertex.z;
			
			maxX += vx;
			maxY += vy;
			maxZ += vz;

		}
		//var vertex : Number3D = new Number3D (maxX/i,maxY/i,maxZ/i);
		var tmp1:Number = maxX/i;
		trace("trace "+tmp1);
		trace("trace "+maxY/i);
		trace("trace "+maxZ/i);
		var m:Matrix3D = new Matrix3D();

		//m.n14= -maxX/i;
//		m.n24= -maxY/i;
//		m.n34= -maxZ/i;
//		var lTranslationMatrix:Matrix3D;
//		var lRotationMatrix:Matrix3D;
//
//		lTranslationMatrix = Matrix3D.translationMatrix(-maxX/i,-maxY/i,0);
		//obj.transform = Matrix3D.multiply( lTranslationMatrix, obj.transform );
		trace("gia tir toa do 1"+obj.x);
		//obj.x =-tmp1;
		//obj.y= -maxZ/i;
		//obj.z =maxY/i;
		//var position:Number3D = new Number3D(-maxX/i,maxY/i,0);
		obj.x =-maxX/i;
		obj.y= maxZ/i;
		obj.z =-maxY/i;
		//obj.transform = Matrix3D.translationMatrix(-maxX/i,0,0);
		trace("gia tir toa do 2"+obj.x);
		trace("gia tir toa do 2"+obj.y);
		trace("gia tir toa do 2"+obj.z);
		}
		public function loadDAE(obj:String):void {
			if(sCustom){
			sCustom.removeChild(object);
			}
			var colorMaterial:ColorMaterial = new ColorMaterial(0x0000ff);
			var colorMaterial2:ColorMaterial = new ColorMaterial(0x000000);
			var matList:MaterialsList =  new MaterialsList();
			matList.addMaterial( colorMaterial,"Change-material");
			matList.addMaterial( colorMaterial2,"_1_-_Default-material");
			//object= null;
			object = new DAE();
			object.load(obj,matList);
			object.scale = 100;
			setInteractiveMaterials(object,true);
			//cCustom.y=100;
			sCustom.addChild(object);
			object.addEventListener(FileLoadEvent.LOAD_COMPLETE, colladaLoaded);
			trace("load lai for dae");
			addEventListener(Event.ENTER_FRAME, render);
			cCustom = new InteractiveCamera3D(vpCustom);
			
		}
		public function changeColor():void{
				
				colorPicker.scaleX=.5;
				colorPicker.scaleY=.5;
           		addChild(colorPicker);
				colorPicker.visible=false;
				colorPicker.x = 270;
				colorPicker.selectedColor = 0x00ff00;
				colorPicker.open();
                colorPicker.addEventListener(ColorPickerEvent.CHANGE, changeHandler);

			//mainViewport.opaqueBackground = 0xffffff;
			//addChild(mainViewport);
				//on load for model option
				//var onLoad:
			}
		private function changeHandler(event:ColorPickerEvent):void {
            updateMaterials();
        }
		private function updateMaterials():void
        {	
			var mc:GouraudMaterial = new GouraudMaterial(light,colorPicker.selectedColor,0x000000);
			// replace material and update events for dae
			mc.interactive=true;
			//var phong:PhongMaterial = new PhongMaterial(light, 0xFF0000, 0x000000,0);
			light.y = 50;
			light.z = 10;
			if(dae1.name!="banhtruoc_left"&&dae1.name!="banhtruoc_right"&&dae1.name!="banhsau_left"&&dae1.name!="banhsau_right")
				object.setChildMaterial(dae1,mc);
     	}
		public function killDAE():void{
			// for each(var child:* in sCustom.children) 
//            {
//				trace("truoc khi remove child "+sCustom.numChildren);
//              //  child.removeEventListener(InteractiveScene3DEvent.OBJECT_CLICK, selectObject3D);
//                //sCustom.userData = null;
//                sCustom.removeChild(child);
//            }
			
			sCustom.removeChild(object);
			object=null;
			dae1=null;
			dae4=null;
			dae3=null;
			dae2=null;
			trace("sau khi remove chlid "+sCustom.numChildren);
			removeEventListener(Event.ENTER_FRAME, render);
			//object=null;
			trace("da remove");
			
		}
	public function setInteractive(targetObject:DisplayObject3D, value:Boolean):void
{
	 if(targetObject.materials.numMaterials>0) {
                for(var i:String in targetObject.materials.materialsByName) {
                    (targetObject.materials.materialsByName[i] as MaterialObject3D).interactive = true;
                }
            } else if(targetObject.material) {
                targetObject.material.interactive = true;
            }
}
		private function colladaLoaded(e:FileLoadEvent):void 
		{
			
			
			cCustom.y = 100;
			//cCustom.moveBackward(1000);
			setInteractiveMaterials(object,true);
			for(var j:int=0;j<text.length;j++){
				if(text[j]==Papervision.nameObject)
					{
						dae1 = object.getChildByName(text[j],true);
						if(text[j]!="khung"){
							isBoolean = true;
							parseMesh(dae1);
						}
						else if(text[j]=="khung")
						{
							dae3=object.getChildByName("default_matden",true);
							
							dae4=object.getChildByName("default_material",true);
			
						}

					}
				else if (text[j]!="khung"&&text[j]!="default_matden"&&text[j]!="default_material")
					{
						dae2=object.getChildByName(text[j],true);
						c_parent=dae2.parent;
						c_parent.removeChild(dae2);
					}
			}
		if(isBoolean== true){
			dae3=object.getChildByName("default_matden",true);
			dae4=object.getChildByName("default_material",true);
			dae5=object.getChildByName("khung",true);
			c_parent= dae3.parent;
			c_parent.removeChild(dae3);
			c_parent= dae4.parent;
			c_parent.removeChild(dae4);
			c_parent= dae5.parent;
			c_parent.removeChild(dae5);
		}
		isBoolean= false;
			
}

		public function render(e:Event):void 
        {	
            renderer.renderScene(sCustom,cCustom,vpCustom);
        }
     }
  }